﻿using System.Text.Json;
using ZGL.Api.Utils;

namespace ZGL.Api.Filters
{
    public class ErrorHandlingMiddleware
    {
        private readonly RequestDelegate _next;

        public ErrorHandlingMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (Exception ex)
            {
                await HandleExceptionAsync(context, ex);
            }
        }

        private Task HandleExceptionAsync(HttpContext context, Exception exception)
        {
            var code = GetStatusCode(exception);
            var result = GetErrorResponse(code, exception);

            context.Response.ContentType = "application/json";
            context.Response.StatusCode = code;

            return context.Response.WriteAsync(result);
        }

        private static int GetStatusCode(Exception exception)
        {
            // 根据异常类型返回不同的状态码，例如：400, 404, 500等
            return exception is KeyNotFoundException ? 404 : 500;
        }

        private static string GetErrorResponse(int statusCode, Exception exception)
        {
            var response = new R(data: null, code: statusCode, message: exception.Message);
            return JsonSerializer.Serialize(response);
        }
    }
}
